// 导出一个axios的实例  而且这个实例要有请求拦截器 响应拦截器
// import axios from 'axios'
// const service = axios.create() // 创建一个axios的实例
// // service.interceptors.request.use() // 请求拦截器
// // service.interceptors.response.use() // 响应拦截器
// export default service // 导出axios实例

// 导入包
import axios from 'axios'
// 按需导入 es6 MessageBox,
import { Message } from 'element-ui'
// 引入路由
import router from '@/router'
// 引入vuex
import store from '@/store'
console.log('当前的store信息是', store)
// console.log('当前的环境变量是', process.env)
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: 'http://ihrm-java.itheima.net/api', // 设置axios请求的基础的基础地址
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
// 请求拦截器
service.interceptors.request.use(
  config => {
    // const token = store.state.user.token
    const token = store.getters.token
    // do something before request is sent
    // 如果当前存有token,就加在请求头上
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
// 响应拦截器
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // axios会自动对后端回来的数据进行包装：额外又补充了一层{data: {后端回来的数据}}
    const data = response.data
    console.log('拦截器中response是', response, data)
    // 后端接口有约定：如果成功，则success是true
    if (data.success) {
      return data
    } else {
      // 如果操作不成功，直接返回错误
      return Promise.reject(new Error(data.message))
    }
  },
  error => {
    if (error.response && error.response.data && error.response.data.code === 10002) {
      Message({
        message: '请重新登陆',
        type: 'error',
        duration: 5 * 1000
      })
      // token失效了
      // 1. 手动执行logout, 删除token
      store.dispatch('user/logout')
      // 2. 回到登陆页
      router.push('/login')
    } else {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }

    return Promise.reject(error)
  }
)

export default service
